package com.huilian.security.sms.impl;


import com.google.gson.Gson;
import com.huilian.security.sms.SmsCodeSender;
import com.huilian.security.sms.common.ServerResponse;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author: 少凡
 * @Date 2018/4/2 17:19
 */
@Slf4j
@Component
public class UcpaasSmsCodeSender implements SmsCodeSender {

    @Override
    public ServerResponse send(String mobile, String content, String templateId) {
        log.info("向手机：" + mobile + "发送内容：" + content);
        JSONObject jsonObject = null;

        EncryptUtil encryptUtil = new EncryptUtil();
        SMSUtils smsUtils = new SMSUtils();

        try {
            String timestamp = DateUtil.dateToStr(new Date(), DateUtil.DATE_TIME_NO_SLASH);

            String sig = smsUtils.getSigParameter(SMSConfig.ACCOUNT_SID, SMSConfig.AUTH_TOKEN, timestamp, encryptUtil);

            String auth = smsUtils.getAuth(SMSConfig.ACCOUNT_SID, timestamp, encryptUtil);
            String param = content;

            TemplateSMS templateSMS = new TemplateSMS();
            templateSMS.setAppId(SMSConfig.APPID);
            templateSMS.setTemplateId(templateId);
            templateSMS.setTo(mobile);
            templateSMS.setParam(param);

            Gson gson = new Gson();
            String body = gson.toJson(templateSMS);

            body = "{\"templateSMS\":" + body + "}";

            StringBuffer sb = new StringBuffer("https://api.ucpaas.com/2014-06-30/Accounts/");
            sb.append(SMSConfig.ACCOUNT_SID)
                    .append("/Messages/templateSMS")
                    .append("?sig=").append(sig);
            String url = sb.toString();

            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = smsUtils.post("application/json", auth, url, httpclient, body, httppost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity, "UTF-8");
                jsonObject = JSONObject.fromObject(result);
            }
            EntityUtils.consume(entity);
            httppost.releaseConnection();
            String respCode = jsonObject.getJSONObject("resp").getString("respCode");

            if (!respCode.equals("000000")) {
                String errMsg = "手号机号码" + mobile + "短信发送失败：" + respCode;
                log.error(errMsg);
                return ServerResponse.createByErrorMessage(errMsg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMessage(e.getMessage());
        }
        return ServerResponse.createBySuccess();
    }
}
